package org.belkodevelop.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.belkodevelop.auth.dto.LoginStatus;
import org.belkodevelop.controller.helper.AuthUtils;
import org.belkodevelop.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api/login.json")
public class AuthController {

    private final Log log = LogFactory.getLog(getClass()); 
    
    @Autowired
    private AuthUtils authUtils;
    
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public LoginStatus getStatus() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && !auth.getName().equals("anonymousUser") && auth.isAuthenticated()) {
            return new LoginStatus(true, auth.getName(), getRolesFromCollectionGrantedAuthority(auth.getAuthorities()));
        } else {
            return new LoginStatus(false, null, null);
        }
    }
    
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public LoginStatus login(@RequestParam("login") String login,
                            @RequestParam("password") String password,
                            @RequestParam(value = "rememberMe", required = false) String rememberMe,
                            HttpServletRequest request, 
                            HttpServletResponse response) {
        boolean rememberMeFlag = rememberMe != null && !rememberMe.equals("") ? true : false;
        try {
            Authentication auth = authUtils.login(login, password, rememberMeFlag, request, response);
            return new LoginStatus(auth.isAuthenticated(), login, getRolesFromCollectionGrantedAuthority(auth.getAuthorities()));
        } catch (AuthenticationException e) {
            log.warn("Error",e);
            return new LoginStatus(false, null, null);
        }
    }

    private List<String> getRolesFromCollectionGrantedAuthority(Collection<GrantedAuthority> grantedAuthorityCollection) {
        List<String> roles = new ArrayList<String>(grantedAuthorityCollection.size());
        for (GrantedAuthority grantedAuthority: grantedAuthorityCollection) {
            roles.add(grantedAuthority.getAuthority());
        }
        return roles;
    }
}